/// API响应数据模型
class ApiResponse<T> {
  final int code;
  final String message;
  final T? data;
  final DateTime timestamp;

  const ApiResponse({
    required this.code,
    required this.message,
    this.data,
    required this.timestamp,
  });

  factory ApiResponse.fromJson(
    Map<String, dynamic> json,
    T? Function(dynamic) fromJson,
  ) {
    // 处理时间戳格式，可能是ISO8601字符串或毫秒时间戳
    DateTime parsedTimestamp;
    try {
      if (json['timestamp'] is String) {
        parsedTimestamp = DateTime.parse(json['timestamp'] as String);
      } else if (json['timestamp'] is int) {
        parsedTimestamp = DateTime.fromMillisecondsSinceEpoch(
          json['timestamp'] as int,
        );
      } else {
        parsedTimestamp = DateTime.now();
      }
    } catch (e) {
      parsedTimestamp = DateTime.now();
    }

    // 安全解析data字段
    T? parsedData;
    try {
      parsedData = json['data'] == null ? null : fromJson(json['data']);
    } catch (e) {
      parsedData = null;
    }

    return ApiResponse<T>(
      code: json['code'] as int,
      message: json['message'] as String,
      data: parsedData,
      timestamp: parsedTimestamp,
    );
  }

  bool get isSuccess => code == 200;
}
